﻿using Architecture.Domain.Services.Interface;
using Architecture.Domian;
using Architecture.Domian.Common;
using Architecture.Domian.DTO;
using Architecture.Domian.Entity;
using Architecture.Repository;
using Architecture.Repository.Interface;

namespace Architecture.Domain.Services.Impl
{
    // 单一模块服务实现
    public class RoleService : IRoleSerivce
    {
        private readonly IRoleRepository _roleRepository;
        private readonly IUserRepository _userRepository;
        private readonly IRepository<UserRoleRelation> _relationRepository;

        public RoleService(IRoleRepository roleRepository, IUserRepository userRepository, IRepository<UserRoleRelation> relationRepository)
        {
            _roleRepository = roleRepository;
            _userRepository = userRepository;
            _relationRepository = relationRepository;
        }

        public async Task<int> RoleInsert(RoleInfo role)
        {
            var exist = await _roleRepository.GetByFuncAsync(x => x.RoleName.Equals(role.RoleName));
            if (exist != null)
            {
                return -1;
            }
            role.CreatePerson = "张三";
            role.CreateDate = DateTime.Now;
            role.RevisePerson = null;
            role.ReviseDate = null;
            role.IsDelete = false;
            var res = await _roleRepository.AddAsync(role);
            return res;
        }

        public async Task<PageResult<RoleInfo>> GetRoleList(int size, int index)
        {
            var roleInfo = await _roleRepository.GetAsync(x => !x.IsDelete);

            int totalCount = roleInfo.Count();
            int pageCount = (int)Math.Ceiling(totalCount * 1.0 / size);
            roleInfo = roleInfo.OrderByDescending(x => x.RoleId).Skip(size * (index - 1)).Take(size).ToList();

            return new PageResult<RoleInfo>
            {
                TotalCount = totalCount,
                PageCount = pageCount,
                Datas = roleInfo.ToList()
            };
        }

        public async Task<int> LogicDelete(int roleId)
        {
            // 删除与该角色相关的用户角色关系
            var relation = await _relationRepository.GetAsync(x => x.RoleId.Equals(roleId));
            _relationRepository.BatchDeleteAsync(relation);
            // 逻辑删除角色信息
            var roleInfo = await _roleRepository.GetByIdAsync(roleId);
            roleInfo.IsDelete = true;
            var res = await _roleRepository.UpdateAsync(roleInfo);
            return res;
        }

        public async Task<RoleInfo> GetRoleInfoByRoleId(int roleId)
        {
            var roleInfo = await _roleRepository.GetByIdAsync(roleId);
            return roleInfo;
        }

        public async Task<int> RoleUpdate(RoleInfo role)
        {
            var exist = await _roleRepository.GetByFuncAsync(x => x.RoleName.Equals(role.RoleName) && x.RoleId.Equals(role.RoleId));
            if (exist != null)
            {
                return -1;
            }
            role.RevisePerson = "李四";
            role.ReviseDate = DateTime.Now;
            var res = await _roleRepository.UpdateAsync(role);
            return res;
        }

        public async Task<List<TreeList>> GetUserTreeListByDepartmentId(int departmentId)
        {
            var res = from a in _userRepository.GetAllAsync().Result
                      select new TreeList
                      {
                          Id = a.UserId,
                          Label = a.LoginName,
                      };
            if (departmentId != 0)
            {
                res = _userRepository.GetAsync(x => x.DepartmentId.Equals(departmentId)).Result.Select(x => new TreeList
                {
                    Id = x.UserId,
                    Label = x.LoginName,
                });
            }
            return res.ToList();
        }

        public async Task<int> UserRoleBatchInsert(int roleId, List<int> userIds)
        {
            var relation = await _relationRepository.GetAsync(x => x.RoleId.Equals(roleId));
            await _relationRepository.BatchDeleteAsync(relation);
            if (userIds.Count == 0) return 1;
            var res = 0;
            foreach (var userId in userIds)
            {
                UserRoleRelation roleRelation = new UserRoleRelation
                {
                    RoleId = roleId,
                    UserId = userId
                };
                res += await _relationRepository.AddAsync(roleRelation);
            }
            return res;
        }


        public async Task<int> Test(int num)
        {

            num++;

            return await Task.FromResult(num);
        }


        public async Task<List<UserRoleDTO>> GetUserListByRoleId(int roleId)
        {
            var userIds = _relationRepository.GetAsync(x => x.RoleId.Equals(roleId)).Result.Select(x => x.UserId).AsQueryable().ToList();
            List<UserRoleDTO> res = new List<UserRoleDTO>();
            foreach (var userId in userIds)
            {
                var userInfo = await _userRepository.GetByIdAsync(userId);
                res.Add(new UserRoleDTO
                {
                    userId = userId,
                    UserName = userInfo.LoginName
                });
            }
            return res;
        }

        public async Task<int> DeleteUserRoleInfo(int roleId, int userId)
        {
            var roleUserInfo = await _relationRepository.GetByFuncAsync(x => x.RoleId.Equals(roleId) && x.UserId.Equals(userId));
            var res = await _relationRepository.DeleteAsync(roleUserInfo);
            return res;
        }
    }
}
